<template>
  <page-header-wrapper :title="false">
    <a-card>
      <div class="table-page-search-wrapper">
        <a-form-model :model="queryParam" layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="客户名称">
                <a-input v-model="queryParam['filter[customer_name]']" placeholder="输入客户姓名" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="合同编号">
                <a-input v-model="queryParam['filter[contract_no]']" placeholder="输入合同编号" />
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="联系电话">
                  <a-input v-model="queryParam['filter[phone]']" placeholder="输入联系电话" />
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="商标类别">
                  <a-select :filter-option="filterOption" v-model="queryParam['filter[sb_category]']" placeholder="选择商标类别">
                    <a-select-option v-for="(item,index) in tmTypeOpts" :key="index" :value="index">{{ item }}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="业务大类">
                  <a-select :filter-option="filterOption" v-model="queryParam['filter[category]']" @change="changeCategory" placeholder="选择业务大类">
                    <a-select-option v-for="(item,index) in categoryOpts" :key="index" :value="index">{{ item }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="业务小类">
                  <a-select :filter-option="filterOption" v-model="queryParam['filter[business_id]']" @change="changeBusiness" placeholder="选择业务小类">
                    <a-select-option v-for="item in businessOpts" :key="item.business_id" :value="item.business_id">{{ item.name }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="进展状态">
                  <a-select :filter-option="filterOption" placeholder="请选择进展状态" @change="changeStatus">
                    <a-select-option v-for="(item,index) in statusOpts" :key="index" :value="index">
                      {{ item }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="开启时间">
                  <a-range-picker v-model="queryParam['open_time_start']" @change="onChange" />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="业务来源">
                  <a-select :filter-option="filterOption" v-model="queryParam['filter[business_type]']" placeholder="请选择进展状态">
                    <a-select-option v-for="(item,index) in typeOpts" :key="index" :value="index">
                      <a-badge :color="index == 1 ? 'green' : 'yellow'" status="processing" />{{ item }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetSearch">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
    <a-card :style="{ marginTop: '10px' }">
      <template v-if="!loading" slot="title">
        <a-row>
          <a-col :span="12">
            <a-button type="primary" :disabled="selectedRowKeys.length === 0" :style="{ marginRight: '5px' }">批量下载</a-button>
            <a-button :style="{ marginRight: '5px' }" @click="getUnread(1)">全部</a-button>
            <a-button @click="getUnread(0)">未读业务({{ statusItems['data_count_unread'] }})</a-button>
          </a-col>
          <a-col :style="{ textAlign: 'right' }" :span="12">
            <a-badge :count="statusItems['data_count_status34']" :style="{ marginLeft: '20px' }">
              <a-button size="small" :type="btnStatus == 'status2_34' ? 'danger' : 'default'" @click="handleFilter('status2_34')">专利未定稿</a-button>
            </a-badge>
            <a-badge :count="statusItems['data_count_status10']" :style="{ marginLeft: '20px' }">
              <a-button size="small" :type="btnStatus == 'status2_1' ? 'danger' : 'default'" @click="handleFilter('status2_1')">材料待交</a-button>
            </a-badge>
            <a-badge :count="statusItems['data_count_status22']" :style="{ marginLeft: '20px' }">
              <a-button size="small" :type="btnStatus == 'status2_5' ? 'danger' : 'default'" @click="handleFilter('status2_5')">材料疑问</a-button>
            </a-badge>
            <a-badge :count="statusItems['data_count_status24']" :style="{ marginLeft: '20px' }">
              <a-button size="small" :type="btnStatus == 'status2_7' ? 'danger' : 'default'" @click="handleFilter('status2_7')">确认材料</a-button>
            </a-badge>
          </a-col>
        </a-row>
      </template>
      <div :style="{ textAlign: 'right', marginBottom: '10px' }"><a-button size="small" type="default" @click="onClear">重置</a-button></div>
      <s-table
        v-if="clear"
        bordered
        ref="table"
        :row-key="(record) => record.cb_id"
        :row-class-name="(record) => { if (record.is_read == 0 || record.status2 == 34) return 'table-color-dust' }"
        :columns="businessColumns"
        :data="businessData"
        :scroll="{ x: 2000 }"
      >
        <div
          slot="filterDropdown"
          slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
          style="padding: 8px"
        >
          <a-input
            v-ant-ref="c => (searchInput = c)"
            :placeholder="`搜索${column.title}`"
            :value="selectedKeys[0]"
            style="width: 188px; margin-bottom: 8px; display: block;"
            @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
            @pressEnter="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
          />
          <a-button
            type="primary"
            icon="search"
            size="small"
            style="width: 90px; margin-right: 8px"
            @click="() => handleSearch(selectedKeys, confirm, column.dataIndex)"
          >
            搜索
          </a-button>
          <a-button size="small" style="width: 90px" @click="() => handleReset(clearFilters)">
            重置
          </a-button>
        </div>
        <template slot="xuhao" slot-scope="text,record,index">
          {{ index + 1 }}
        </template>
        <template slot="business_type" slot-scope="text">
          <a :title="text == '1' ? '转移业务' : '我的业务'"><a-badge :color="text == 1 ? 'yellow' : 'green'" status="processing" /></a>
        </template>
        <template slot="contract_no" slot-scope="text,record">
          <a title="点击查看合同下所有业务" @click="onModal(text)">{{ text }}</a><br>
          <a @click="toDetail(record.cb_id)">{{ record.business_no }}</a>
        </template>
        <template slot="category" slot-scope="text">
          {{ categoryOpts[text] }}
        </template>
        <template slot="sb_name" slot-scope="text,record">
          {{ text }}{{ record.zl_name }}{{ record.bq_name }}
        </template>
        <template slot="sb_category" slot-scope="text">
          {{ tmTypeOpts[text] }}
        </template>
        <template slot="price" slot-scope="text">
          <a-tag color="blue">{{ text }}</a-tag>
        </template>
        <template slot="customer_name" slot-scope="text,record">
          <a @click="toCustomerDetail(record.customer_id)">{{ text }}</a>
        </template>
        <template slot="phone" slot-scope="text,record">
          <a-button-group>
            <a-popover trigger="hover">
              <template slot="content">
                <p>电话：{{ record.phone }}<a-divider type="vertical" /><a-icon class="copy" :data-clipboard-text="record.phone" type="copy" @click="copy" /></p>
                <p>微信：{{ record.wechat }}<a-divider type="vertical" /><a-icon class="copy" :data-clipboard-text="record.wechat" type="copy" @click="copy" /></p>
              </template>
              <a-button size="small" type="primary" ghost style="width: 100px;overflow: hidden">{{ text }}</a-button>
            </a-popover>
            <a-button size="small" type="primary" icon="phone" @click="makePhone(record.customer_id)"></a-button>
          </a-button-group>
        </template>
        <template slot="status2" slot-scope="text,record">
          <div v-if="record.state_file_url !== ''">
            <div>
              <a :href="record.state_file_url" target="_blank"><a-icon :style="{ fontSize: '18px', color: '#1890ff' }" type="file-pdf" /></a>
              <a @click="downFile(record.state_file_url, record.state_file_name)"><a-icon :style="{ fontSize: '18px', color: '#1890ff' }" type="download" /></a>
              {{ record.state_name }}
            </div>
            <div>{{ record.state_file_name }}</div>
          </div>
          <div v-else>
            <a-button v-if="text == 24" type="danger" icon="edit" size="small" @click="getResult(record.cb_id)">{{ record.status2_name }}</a-button>
            <a-button v-if="text == 10 || text == 22" type="danger" icon="edit" size="small" @click="getSubmitFill(record.cb_id)">{{ record.status2_name }}</a-button>
            <a-button v-if="text == 34" type="danger" icon="edit" size="small" @click="getConfirm(record.cb_id)">{{ record.status2_name }}</a-button>
            <a-button
              ghost
              v-if="text == 20 || text == 26 || text == 35 || text == 36"
              type="danger"
              size="small"
              @click="getSubmitFill(record.cb_id)"
            >
              {{ record.status2_name }}
            </a-button>
            <a-button
              ghost
              v-if="text == 30"
              type="primary"
              size="small"
              @click="getSubmitFill(record.cb_id)"
            >
              {{ record.status2_name }}
            </a-button>
            <a-button v-if="text == 40" type="primary" size="small" @click="getSubmitFill(record.cb_id)">{{ record.status2_name }}</a-button>
            <a-button v-if="text == 50" type="dashed" size="small" @click="getSubmitFill(record.cb_id)">{{ record.status2_name }}</a-button>
          </div>
        </template>
        <template slot="action" slot-scope="text,record">
          <a-button size="small" type="primary" @click="toDetail(record.cb_id)">查看</a-button>
        </template>
      </s-table>
    </a-card>
    <fill-modal v-if="visible" :fill-key="fillKey" :from-source="'1'" @submit="handleSubmit" @cancel="handleCancel"></fill-modal>
    <confirm-modal v-if="visible2" :fill-key="fillKey" @submit="handleSubmit" @cancel="confirmCancel"></confirm-modal>
    <phone-modal v-if="visible3" :customer-id="customerId" @cancel="modalExit"></phone-modal>
    <patent-modal v-if="visible5" :fill-key="fillKey" @submit="submitPatent" @cancel="patentExit"></patent-modal>
    <a-modal
      v-if="visible4"
      v-model="visible4"
      title="合同信息"
      :width="1000"
      :footer="null"
    >
      <a-descriptions>
        <a-descriptions-item label="客户姓名">
          <a title="点击可以跳到客户详情" @click="toCustomerDetail(contractInfo.customer_data.customer_id)">{{ contractInfo.customer_data.customer_name }}</a>
        </a-descriptions-item>
        <a-descriptions-item label="联系电话">
          <a title="点击拨打电话" @click="makePhone(contractInfo.customer_data.customer_id)">{{ contractInfo.customer_data.phone2 }}</a>
        </a-descriptions-item>
        <a-descriptions-item label="签订时间">
          {{ contractInfo.customer_data.check_time }}
        </a-descriptions-item>
        <a-descriptions-item label="合同金额">
          {{ contractInfo.customer_data.amount }}
        </a-descriptions-item>
        <a-descriptions-item label="代理费">
          {{ contractInfo.customer_data.agency_fee }}
        </a-descriptions-item>
        <a-descriptions-item label="发票">
          否
        </a-descriptions-item>
        <a-descriptions-item label="地址">
          {{ contractInfo.customer_data.address }}
        </a-descriptions-item>
      </a-descriptions>
      <a-divider />
      <a-table
        bordered
        :show-header="false"
        :row-key="(record) => record.cb_id"
        :columns="modalColumns"
        :data-source="contractInfo.business_data"
        :pagination="false"
      >
        <template slot="xuhao" slot-scope="text,record,index">
          {{ index + 1 }}
        </template>
        <template slot="customer_name" slot-scope="text,record">
          <a @click="toCustomerDetail(record.customer_id)">{{ text }}</a>
        </template>
        <template slot="price" slot-scope="text,record">
          官费：{{ record.official_fee }}<br>
          代理费：{{ record.price - record.official_fee }}
        </template>
        <template slot="action" slot-scope="text,record">
          <a-button size="small" type="primary" @click="toDetail(record.cb_id)">查看</a-button>
        </template>
      </a-table>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
  import Clipboard from 'clipboard'
  import { STable, Ellipsis, PhoneModal } from '@/components'
  import businessColumns from '@/columns/business'
  import { getBusinessName, getCount, getList, getStatus, postFill, getContractInfo } from '@/api/business'
  import ConfirmModal from '@/views/business/components/ConfirmModal'
  import FillModal from '@/views/business/components/FillModal'
  import PatentModal from '@/views/business/components/PatentModal'
  import apis from '@/api'

  export default {
    components: {
      PatentModal,
      PhoneModal,
      ConfirmModal,
      FillModal,
      Ellipsis,
      STable
    },
    name: 'BusinessList2',
    data () {
      return {
        advanced: true,
        selectedRowKeys: [],
        businessColumns: businessColumns.tmColumns,
        modalColumns: businessColumns.modal,
        businessData: parameters => {
          return getList(Object.assign(parameters, this.queryParam)).then(res => {
            this.categoryOpts = res.result.business_category_opts
            this.typeOpts = res.result.business_type_opts
            this.tmTypeOpts = res.result.sb_category_opts
            return res.result
          })
        },
        queryParam: {},
        statusItems: {},
        statusOpts: {},
        categoryOpts: {},
        businessOpts: {},
        typeOpts: {},
        tmTypeOpts: {},
        loading: false,
        filteredInfo: null,
        sorterInfo: null,
        visible: false,
        visible2: false,
        visible3: false,
        visible4: false,
        visible5: false,
        fillKey: '',
        clear: true,
        searchInput: null,
        searchText: '',
        searchedColumn: '',
        openTime: '',
        customerId: '',
        contractInfo: {},
        inputSource: {},
        btnStatus: '',
        confirmForm: {}
      }
    },
    activated () {
      if (this.$route.params.type) {
        this.handleFilter(this.$route.params.type)
      }
    },
    created () {
      this.getPageCount()
    },
    methods: {
      getPageCount () {
        this.loading = true
        getCount(0).then(res => {
          this.statusItems = res.result
        }).finally(() => {
          this.loading = false
        })
      },
      changeCategory (value) {
        this.queryParam['filter[category]'] = value
        this.getBusinessName(value)
      },
      changeBusiness (value) {
        this.queryParam['filter[business_id]'] = value
        this.getStatus(value)
      },
      changeStatus (value) {
        this.queryParam['filter[status2_state]'] = value
      },
      getBusinessName (id) {
        getBusinessName(id).then(res => {
          this.businessOpts = res.result.items
        })
      },
      toCustomerDetail (id) {
        this.visible4 = false
        this.$router.push({ name: 'CustomerDetail', params: { id } })
      },
      getStatus (status) {
        getStatus(status).then(res => {
          this.statusOpts = res.result.items
        })
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      },
      onSelectChange (selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys
      },
      onClear () {
        this.clear = false
        this.$nextTick(function () {
          this.clear = true
        })
      },
      onModal (no) {
        const app = this
        getContractInfo(no).then(res => {
          if (res.status === 0) {
            app.contractInfo = res.result
            app.visible4 = true
          } else {
            app.$warning({
              title: res.msg
            })
          }
        })
      },
      resetSearch () {
        this.btnStatus = ''
        this.queryParam = {}
        this.$refs.table.refresh(true)
      },
      getSubmitFill (id) {
        this.fillKey = id
        this.visible = true
      },
      getResult (id) {
        this.fillKey = id
        this.visible2 = true
      },
      getConfirm (id) {
        this.fillKey = id
        this.visible5 = true
      },
      handleSubmit1 (form) {
        const app = this
        form['cb_id'] = app.fillKey
        postFill(form).then(res => {
          if (res.status === 0) {
            app.$refs.table.refresh()
            app.handleCancel1()
          } else {
            app.$warning({
              title: res.msg
            })
          }
        })
      },
      handleSubmit (form) {
        const app = this
        form['cb_id'] = app.fillKey
        postFill(form).then(res => {
          if (res.status === 0) {
            app.$refs.table.refresh()
            app.handleCancel()
            app.confirmCancel()
          } else {
            app.$warning({
              title: res.msg
            })
          }
        })
      },
      submitPatent (form) {
        const app = this
        form['cb_id'] = app.fillKey
        postFill(form).then(res => {
          if (res.status === 0) {
            app.$refs.table.refresh()
            app.patentExit()
          } else {
            app.$warning({
              title: res.msg
            })
            return false
          }
        })
      },
      handleCancel1 (visible) {
        this.visible2 = visible
        this.getPageCount()
      },
      handleCancel (visible) {
        this.getPageCount()
        this.visible = visible
      },
      confirmCancel (visible) {
        this.getPageCount()
        this.visible2 = visible
      },
      downFile (value, filename) {
        window.open(apis.Download + '?value=' + value + '&filename=' + filename)
      },
      handleSearch (selectedKeys, confirm, dataIndex) {
        confirm()
        this.searchText = selectedKeys[0]
        this.searchedColumn = dataIndex
      },
      getUnread (read) {
        if (read === 0) {
          this.queryParam['filter[is_read]'] = read
          this.$refs.table.refresh()
        } else {
          delete this.queryParam['filter[is_read]']
          this.$refs.table.refresh()
        }
      },
      handleReset (clearFilters) {
        clearFilters()
      },
      handleFilter (status) {
        if (this.btnStatus === status) {
          delete this.queryParam['filter[status2_state]']
          this.btnStatus = ''
          this.$refs.table.refresh(true)
        } else {
          this.btnStatus = status
          this.queryParam['filter[status2_state]'] = status
          this.$refs.table.refresh(true)
        }
      },
      onChange (date, dateString) {
        this.queryParam['filter[open_time_start]'] = dateString[0]
        this.queryParam['filter[open_time_end]'] = dateString[1]
      },
      toDetail (id) {
        this.visible4 = false
        this.$router.push({ name: 'BusinessDetail', params: { id } })
      },
      makePhone (id) {
        this.customerId = id
        this.visible3 = true
      },
      modalExit (visible) {
        this.visible3 = visible
      },
      patentExit (visible) {
        this.visible5 = visible
      },
      copy () {
        const clipboard = new Clipboard('.copy')
        clipboard.on('success', e => {
          this.$message.success('复制成功')
        })
        clipboard.on('error', e => {
          this.$message.error('复制失败')
        })
      },
      filterOption (input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        )
      }
    }
  }
</script>

<style scoped>
  /deep/ .ant-statistic-content {
    font-size: 16px;
    color: #f00;
  }
  /deep/ .ant-table-tbody > tr.table-color-dust {
    background-color: #ffcccc;
  }

</style>
